 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;
using Microsoft.Reporting.WebForms;

namespace MedicWeb.forms.Reports.Print {
    public partial class Print : SessionPage {
        protected void Page_Load(object sender, EventArgs e) {
            var ms = new MainService();
            string type = Request.QueryString["type"];
            int id = Convert.ToInt32(Request.QueryString["id"]);
            PrintSettings printSettings = null;
            string html = "";
            if (typeof(PrintOrder).ToString().Equals(type)) {
                PrintOrder printOrder = ms.GetPrintOrder(GetSession(), new MedicService.Order(){Id = id});
                printSettings = printOrder.Settings;
                html = printOrder.Html;
            } else if (typeof(PrintAttestatProtocol).ToString().Equals(type)) {
                PrintAttestatProtocol print = ms.GetPrintAttestatProtocol(GetSession(), new Doctor() { Id = id });
                printSettings = print.Settings;
                html = print.Html;
            } else if (typeof(PrintExtract).ToString().Equals(type)) {
                PrintExtract print = ms.GetPrintExtract(GetSession(), new Doctor() { Id = id });
                printSettings = print.Settings;
                html = print.Html;
            } else if (typeof(PrintProfileProtocol).ToString().Equals(type)) {
                PrintProfileProtocol print = ms.GetPrintProfileProtocol(GetSession(), new Doctor() { Id = id });
                printSettings = print.Settings;
                html = print.Html;
            } else if (typeof(PrintSertificate).ToString().Equals(type)) {
                PrintSertificate print = ms.GetPrintSertificate(GetSession(), new Doctor() { Id = id });
                printSettings = print.Settings;
                html = print.Html;
            } else if (typeof(PrintInvoice).ToString().Equals(type)) {

            } else if ("complex".Equals(type)) {
                PrintAttestatProtocol pap = ms.GetPrintAttestatProtocol(GetSession(), new Doctor() { Id = id });
                PrintProfileProtocol ppp = ms.GetPrintProfileProtocol(GetSession(), new Doctor() { Id = id });
                html = pap.Html;
                html += "<formfeed suppress=\"off\"></formfeed>";
                html += ppp.Html;
                printSettings = pap.Settings;
            }
            if (!IsPostBack) {
                Editor.Text = html;
            }
            if (printSettings != null) {
                var rep = Editor.Text;
                //rep.Split(new string[]{""}, StringSplitOptions.)
                //var txt = Regex.Replace(rep, "<hr[^>]*>", "<formfeed suppress=\"off\"></formfeed>");
                
                string txt = rep.Replace("<div style=\"page-break-after: always;\">", "<div style=\"page-break-after: always;\"><formfeed suppress=\"off\"></formfeed>");
                string work = print(txt, printSettings);
                Response.ContentType = "application/pdf";

                if ("complex".Equals(type)) {
                    var pdfMerge = new PdfMerge();
                    pdfMerge.AddDocument(work);
                    Doctor doctor = ms.LoadDoctor(GetSession(), id);
                    PrintInvoice printInvoice = ms.GetPrintInvoice(GetSession(), doctor);
                    var reportViewer = new ReportViewer();
                    reportViewer.ProcessingMode = ProcessingMode.Local;
                    reportViewer.LocalReport.ReportPath = @"forms\Reports\Invoice\ReportInvoice.rdlc";
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Accepter", printInvoice.Accepter));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("BIK", printInvoice.BIK));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Bank", printInvoice.Bank));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("INN", printInvoice.INN));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("KPP", printInvoice.KPP));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("SP", printInvoice.SP));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Ksch", printInvoice.Ksch));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Ls", printInvoice.Ls));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Summ", printInvoice.Summ));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Vid", printInvoice.Vid));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("FIO", doctor.Surname + " " + doctor.Name + " " + doctor.Patronymic));
                    reportViewer.LocalReport.SetParameters(new ReportParameter("Address", doctor.Address));
                    reportViewer.LocalReport.Refresh();
                    byte[] render = reportViewer.LocalReport.Render("PDF");
                    pdfMerge.AddDocument(render);

                    string complex = System.IO.Path.GetTempPath() + GetSession().SessionId + "\\complex.pdf";
                    if (File.Exists(complex)) {
                        File.Delete(complex);
                    }
                    pdfMerge.Merge(complex);
                    Response.WriteFile(complex);
                } else {
                    //Response.ContentType = "text/html";
                    Response.WriteFile(work);
                    //Response.WriteFile(s + "\\report.html");
                }
                Response.End();
            }

        }

        private string print(string text, PrintSettings settings) {
            bool result = false;
            string message = null;
            string temp = System.IO.Path.GetTempPath();
            //string s = Directory.GetCurrentDirectory().ToString();
            //string work = Server.MapPath("~/work/"+GetSession().SessionId+"/");
            string work = temp + GetSession().SessionId;
            string bin = Server.MapPath("~/bin/");
            bool exists = System.IO.Directory.Exists(work);
            if (exists) {
                File.Delete(work + "\\report.html");
                File.Delete(work + "\\report.pdf");
            }else {
                System.IO.Directory.CreateDirectory(work);
            }


            var fs = new FileStream(work + "\\report.html", FileMode.OpenOrCreate, FileAccess.Write);

            var sw = new StreamWriter(fs);
            sw.WriteLine(text);
            sw.Close();

            //string test = "\"" + s + "\\php-min\\scripts\\test.php" + "\"";
            string convert = "\"" + bin + "\\php-min\\scripts\\createpdf.php" + "\"";
            string filein = "\"" + work + "\\report.html" + "\"";
            string fileout = "\"" + work + "\\report.pdf" + "\"";

            string format = settings.Format;
            string margin_left = "" + settings.MarginLeft;
            string margin_right = "" + settings.MarginRight;
            string margin_top = "" + settings.MarginTop;
            string margin_bottom = "" + settings.MarginBottom;
            string orientation = "" + settings.Orientation;

            string mirrorMargins = "" + settings.DoubleSided;

            string php = "\"" + bin + "\\php-min\\php.exe" + "\"";
            string args = " -f " + convert 
                            + " " + filein 
                            + " " + fileout
                            + " " + format.Trim() + ("L".Equals(orientation) ? "-L":"")
                            + " " + margin_left
                            + " " + margin_right
                            + " " + margin_top
                            + " " + margin_bottom
                            + " " + orientation
                            + " " + mirrorMargins;
            //Process process = Process.Start(php, args);
            //process.WaitForExit();
            try {
                var p = new Process();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;

                p.StartInfo.FileName = php;
                p.StartInfo.Arguments = args;


                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;

                p.Start();
                p.WaitForExit();

                message = p.StandardError.ReadToEnd();

                if (string.IsNullOrEmpty(message)) {
                    message = p.StandardOutput.ReadToEnd();
                } else {
                    Debug.WriteLine(message);
                    // sometime even there is some error message
                    //the conversion still succeeded
                }
                result = true;
            } catch (Exception ee) {
                //logging
            }
            // return result;
            return work + "\\report.pdf";
        }
    }
}